
#include "defines.h"
#include "video/Device.h"

#pragma comment(lib,"d3d9.lib")
#ifdef _DEBUG
#pragma comment(lib,"d3dx9d.lib")
#else
#pragma comment(lib,"d3dx9.lib")
#endif

namespace KEngine
{
	Device::Device():_d3d(0),_device(0)
	{
		memset(&_backBufferDesc,0x00,sizeof(_backBufferDesc));
		memset(&_caps, 0x00 ,sizeof(_caps));
	}

	Device::~Device()
	{
		
		KSafeRelease(_device);
		KSafeRelease(_d3d);
	}

	bool Device::createDevice(HWND wnd)
	{
		if (NULL == (_d3d = Direct3DCreate9(D3D_SDK_VERSION)))
			return false;

		D3DPRESENT_PARAMETERS d3dpp;
		ZeroMemory(&d3dpp, sizeof(d3dpp));
		d3dpp.Windowed = TRUE;
		d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
		d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
		d3dpp.EnableAutoDepthStencil = TRUE; 
		d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
		d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;

		if (FAILED(_d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, wnd,
			D3DCREATE_MIXED_VERTEXPROCESSING,
			&d3dpp, &_device)))
		{
			return false;
		}

		_setBackBufferDesc();
		_setDeviceCaps();

		return true;
	}

	void Device::_setBackBufferDesc()
	{
		ID3DSurface* backBuffer = NULL;
		_device->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backBuffer);
		backBuffer->GetDesc(&_backBufferDesc);
		KSafeRelease(backBuffer);
	}

	void Device::_setDeviceCaps()
	{
		_device->GetDeviceCaps(&_caps);
	}

};
